<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
      <BasicForm @register="registerForm" @eventFormModel="eventFormModel">
        <template #formFooter v-if="dataSource.length">
            <h2 style="font-size:16px">成本计算器</h2>
            <a-table style="width:100%" bordered :dataSource="dataSource" :columns="columnss" :pagination="false">
                <template #bodyCell="{ column, record }">
                    <template v-if="column.key === 'costStatus'">
                        <a-tag v-if="record.costStatus == 1" color="green">正常</a-tag>
                        <a-tag v-if="record.costStatus == 2" color="orange">接近阈值</a-tag>
                        <a-tag v-if="record.costStatus == 3" color="red">接近预警值</a-tag>
                    </template>
                </template>
            </a-table>
        </template>
        <template #projectId="{model, field}">
            <a-select
                v-model.value="projectId"
                :placeholder="projectName"
                style="width: 100%"
                :options="options"
                @change="handleChange"
            ></a-select>
        </template>
      </BasicForm>
      <VerifyInfo :verifyType="7" ref="childRef"/>
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import VerifyInfo from './verifyInfo.vue'
    import { twoDecimal, notEmpty } from '@/utils/tool'
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { useMessage } from '/@/hooks/web/useMessage';
    import {formSchema} from '../MonsterOtherCostSubmit.data';
    import {saveOrUpdate, projectList} from '../MonsterOtherCostSubmit.api';
    import {queryCurrentCostBudget} from '../MonsterSupplierCostSubmit.api';
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const options:any = ref([])
    const projectId = ref('')
    const project = ref('')
    const dataSource = ref<any>([])
    const oldDataSource = ref('')
    let isSet = true
    const projectName = ref('选择项目')
    let ids
    const isType = ref('add')
    const childRef = ref()
    const columnss = ref([
        {
            title: '年度成本总额',
            dataIndex: 'totalCost',
            key: 'totalCost',
        },{
            title: '累计已用',
            dataIndex: 'totalAmount',
            key: 'totalAmount ',
        },
        {
            title: '累计剩余',
            dataIndex: 'remainderBudget',
            key: 'remainderBudget',
        },
        {
            title: '当前付款',
            dataIndex: 'payAmount',
            key: 'payAmount',
        },
        {
            title: '当前预算状态',
            dataIndex: 'costStatus',
            key: 'costStatus',
        },
    ])

    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        dataSource.value = []
        oldDataSource.value = ''
        projectId.value = data.record && data.record.projectId ? data.record.projectId : ''
        projectName.value = '选择项目'
        isSet = true
        ids = ''
        isType.value = data.isType
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});1
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
            await list(data.record)
            childRef.value.childMethod(data.record)
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
        }else {
            childRef.value.childMethod()
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            const { createMessage } = useMessage()
            let old = oldDataSource.value ? JSON.parse(oldDataSource.value) : {}
            // 如果指定属性为空，则返回 false
            if(!notEmpty(values, ['otherProjectType', 'totalAmount']) || !projectId.value) {
                return createMessage.warn('请完善信息')
            }
            if( dataSource.value[0].remainderBudget <=0) {
                return createMessage.warn('申请额度超出预算，无法提交')
            }
            let f = values.uploadFile ? JSON.parse(values.uploadFile) : []
            let file:any = []
            f.forEach((url) => {
                file.push({
                    annexName: url.fileName,
                    annexType: url.fileType,
                    url: url.filePath,
                })
            })
            values.uploadFile = JSON.stringify(file)
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(Object.assign(values,{annex:JSON.stringify(file),status: 1,projectId:projectId.value,project:project.value}), isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }

    function handleChange (id) {
        project.value = options.value.filter(e => e.value == id)[0].label
        projectId.value = id
        isSet = true
        list({projectId:id})
    }

    async function list (item) {
        let res = await queryCurrentCostBudget({operateType:2,submitType:4,projectId:item.projectId,id:item.id,payAmount: item.totalAmount ? item.totalAmount : 0})//.then(res => {
            dataSource.value = [res]
            oldDataSource.value = JSON.stringify(res)
            dataSource.value[0].payAmount = item.totalAmount ? item.totalAmount : 0
        // })
    }

    async function eventFormModel (e) {
        if(isType.value =='info') {
            setTimeout(() => {
                isType.value = 'add'
            },1000)
            return
        }
        options.value = []
        if(e && e.projectId) {
            await list(e)
        }
        // 1 人力
        if(e.otherProjectType !=ids && isSet) {
            ids = e.otherProjectType
            let hr = await projectList({type: e.otherProjectType == 1 ? 2 : 3})
            isSet = false
            hr.forEach((i:any) => {
                options.value.push({
                    ...i,
                    value: i.projectId,
                    label: i.projectName
                })
                if(i.projectId == projectId.value) {
                    projectName.value = i.projectName
                }
            })
            isSet = true
        }
        if(e.totalAmount && dataSource.value.length) {
            const { createMessage } = useMessage()
            let old = JSON.parse(oldDataSource.value)

            // if(dataSource.value[0].totalCost - dataSource.value[0].totalAmount - e.totalAmount > 0 ){
            if(Number(old.remainderBudget) + Number(dataSource.value[0].totalAmount) - Number(e.totalAmount) > 0 ){
                dataSource.value[0].remainderBudget = twoDecimal(Number(old.remainderBudget) - Number(e.totalAmount))
                dataSource.value[0].totalAmount = twoDecimal(Number(old.totalAmount) + Number(e.totalAmount))
            } else {
                dataSource.value[0].remainderBudget = old.remainderBudget
            }

            if(old.totalCost - old.totalAmount - e.totalAmount < 0 ){
                //不允许申报
                createMessage.warn('超出预算限额，无法申报')
                dataSource.value[0].remainderBudget = 0
            }
            let cost = Number(dataSource.value[0].remainderBudget) / Number(dataSource.value[0].totalCost)
            console.log('totalCost',dataSource.value[0].totalCost)
            console.log('totalAmount',e.totalAmount)
            console.log('remainderBudget',dataSource.value[0].remainderBudget)
            console.log('cost',cost)
            console.log('remindThreshold',dataSource.value[0].remindThreshold)
            console.log('warningThreshold',dataSource.value[0].warningThreshold)
     /*     totalCost 60000
          MonsterOtherCostSubmitModal.vue:199 totalAmount 45000
          MonsterOtherCostSubmitModal.vue:200 remainderBudget 15000
          MonsterOtherCostSubmitModal.vue:201 cost -0.5*/
            if(cost < dataSource.value[0].remindThreshold && cost > dataSource.value[0].warningThreshold) {
                // createMessage.warn('无法扣除费用')
                console.log('costStatus',2)
                dataSource.value[0].costStatus = 2
            }
           if(cost < dataSource.value[0].warningThreshold) {
                dataSource.value[0].costStatus = 3
            }
            else {
                dataSource.value[0].costStatus = 1
            }
            dataSource.value[0].payAmount = e.totalAmount
        }
        if(!e.totalAmount && dataSource.value.length) {
            dataSource.value[0].payAmount = ''
        }
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
